// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// I [author] rhyme_lph
// y [email]  rhymelph@gmail.com
// i [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/coa_entity.dart';
import 'package:finance_app/src/provider/setting/account/set_opening_balance_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_white_button.dart';
import 'package:finance_app/src/widgets/common/expandable.dart';
import 'package:finance_app/src/widgets/common/normal_table_pro.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/chart_account_open_balance_item.dart';
import 'package:finance_app/src/widgets/list_item/list_expandable_item.dart';
import 'package:finance_app/src/widgets/list_item/time_select_item.dart';
import 'package:flutter/material.dart';

@RouterMeta(paramName: "setOpeningBalancePage")
class SetOpeningBalancePage extends StatefulWidget {
  @override
  _SetOpeningBalancePageState createState() => _SetOpeningBalancePageState();
}

class _SetOpeningBalancePageState extends State<SetOpeningBalancePage>
    with PagePresenter<SetOpeningBalancePage, SetOpeningBalanceProvider> {
  List<ExpandableController> expandControllerList = [
    ExpandableController(initialExpanded: true),
    ExpandableController(initialExpanded: true),
  ];

  @override
  void initState() {
    provider.searchController.addListener(() {
      if (provider.searchController.text.isNotEmpty) {
        for (ExpandableController controller in expandControllerList) {
          controller.expanded = true;
        }
      }
      provider.update();
    });
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.set_opening_balance,
      );

  @override
  Widget get buildWidget => Stack(
        children: [
          _buildListItem(),
          _buildBottomBar(),
        ],
      );

  Widget _buildListItem() => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            TimeSelectItem(
                title: S.current.as_at,
                value: Config.currentFY.startDate == null
                    ? Config.settingInfo.dateFormat.toUpperCase() ??
                        "DD MMM YYYY"
                    : DateTimeUtils.formatDateTimeString(
                        Config.currentFY.startDate),
                onTap: null),
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            AppSpaces.h20,
            Expanded(
              child: ListView(
                children: [
                  NormalTableProHeader(
                    items: [
                      S.current.account,
                      '${S.current.opening_balance} (${Config.defaultCurrency.key})',
                    ],
                  ),
                  listBuilder<List<CoaByGroupEntity>>(
                    selector: (_, __) => List.from(__.data),
                    builder: (BuildContext context,
                        List<CoaByGroupEntity> value, Widget child) {
                      List<Widget> children = [];
                      for (final item in value) {
                        final data = item.coaAccountDetail
                            .where((element) =>
                                RegExpUtils.getSearchRegExp(
                                        provider.searchController.text)
                                    .hasMatch(element.name) ||
                                RegExpUtils.getSearchRegExp(
                                        provider.searchController.text)
                                    .hasMatch(element.accountCode))
                            .toList();

                        if (data.length > 0) {
                          children.add(ListExpandableItem(
                            controller: expandControllerList[
                                provider.data.indexOf(item)],
                            title: item.groupName,
                            content: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: data
                                    .map((e) => ChartAccountOpenBalanceItem(
                                          title: e.externalAccountCode,
                                          name: e.name,
                                          isChild: e.parentAccountId != 0,
                                          amount: '${e.openBalance}',
                                          hardAmount:
                                              e.hardValue?.toStringAsFixed(2),
                                          onUpdateValue: (s) =>
                                              provider.updateValue(e, s),
                                          enabled: e.accountCode != '3200',
                                          status: e.crdrNature == "DR"
                                              ? S.current.debit
                                              : S.current.credit,
                                        ))
                                    .toList()),
                          ));
                        }
                      }
                      children.addAll([
                        AppSpaces.h25,
                        _buildTotalWidget(),
                      ]);
                      children.add(AppSpaces.h90);
                      return Column(
                        children: children,
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      );

  Widget _buildBottomBar() => Positioned(
      bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
      left: 0.0,
      right: 0.0,
      child: Visibility(
        visible: MediaQuery.of(context).viewInsets.bottom == 0,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            NormalFloatTextWhiteButton(
              title: S.current.cancel,
              onTap: provider.onCancel,
            ),
            SizedBox(
              width: getDp(15),
            ),
            NormalFloatTextButton(
              title: S.current.save,
              onTap: () => provider.onSave(),
            ),
          ],
        ),
      ));

  Widget _buildTotalWidget() => Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          DefaultTextStyle(
            style: TextStyle(
              color: aceDarkGrayColor,
              fontSize: getSp(16),
              fontWeight: FontWeight.w400,
              height: 22 / 14,
              fontFamily: "DinRoundPro",
            ),
            child: Column(
              children: [
                Text(S.current.total_debit),
                AppSpaces.h15,
                Text(S.current.total_credit),
                AppSpaces.h15,
                Text(S.current.difference),
              ],
            ),
          ),
          AppSpaces.w10,
          DefaultTextStyle(
            style: TextStyle(
              color: aceDarkGrayColor,
              fontSize: getSp(16),
              fontWeight: FontWeight.w700,
              height: 22 / 14,
              fontFamily: "DinRoundPro",
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                listBuilder<String>(
                  selector: (_, __) =>
                      CashUtils.formatCashAmount(__.debitTotal),
                  builder: (BuildContext context, String value, Widget child) =>
                      Text('SGD $value'),
                ),
                AppSpaces.h15,
                listBuilder<String>(
                  selector: (_, __) =>
                      CashUtils.formatCashAmount(__.creditTotal),
                  builder: (BuildContext context, String value, Widget child) =>
                      Text('SGD $value'),
                ),
                AppSpaces.h15,
                listBuilder<String>(
                  selector: (_, __) =>
                      CashUtils.formatCashAmount(__.difference),
                  builder: (BuildContext context, String value, Widget child) =>
                      Text('SGD $value'),
                ),
              ],
            ),
          ),
          AppSpaces.w35,
        ],
      );
}
